package com.antler.smt.portal.Interceptor;

import com.antler.smt.constant.InterceptConstant;
import com.antler.smt.constant.InterceptorConstant;
import com.antler.smt.entity.MemberEntity;
import com.antler.smt.portal.utils.TokenUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;

/**
 * 拦截器实现
 *
 * @author vic
 * @date 2018/4/3 10:50
 */
public class AuthorityInterceptor implements HandlerInterceptor {

    String actionStr = InterceptorConstant.ACTIONS;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String url = request.getRequestURL().toString();
        String[] actions = actionStr.split(",");
        for (String action : actions) {
            if (url.contains(action)) {
                String token = null;
                Cookie[] cookies = request.getCookies();
                if (cookies != null && cookies.length > 0) {
                    for (Cookie cookie : cookies) {
                        if (cookie.getName().equals("token")) {
                            token = cookie.getValue();
                            break;
                        }
                    }
                }
                if (token != null) {
                    MemberEntity currentMember = TokenUtil.getMemberByToken(token);
                    if (currentMember == null) {
                        return false;
                    }
                } else {
                    return false;
                }
                break;
            }
        }
        //拦截莫名其妙的连接
        String[] urls = InterceptConstant.URL_BAD.split(",");
        boolean[] flag = new boolean[]{false};
        Arrays.asList(urls).stream()
                .forEach(e -> {
                    if(StringUtils.contains(url,e)){
                        flag[0] = true;
                        return;
                    }
                });
        if(flag[0]){
            flag[0] = false;
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
